import {
  Button, Col, Form, Input, message, Modal, Row, Select, Spin, Tag,
} from 'antd'
import { history } from '@umijs/max'
import React, { PureComponent } from 'react'
import {
  getAssociatedTasks, getPreviewData, getTableList, saveIndexCorrelation,
} from './api'
import PreviewModal from './previewModal'
import BloodRelationshipMap from './bloodRelationshipMap'
import styles from './index.less'

const { Item } = Form
const { Option } = Select
const calTimeGranularityStr = (timeGranularity) => {
  let str = ''
  switch (timeGranularity) {
    case 'day':
      str = '日'
      break
    case 'week':
      str = '周'
      break
    case 'month':
      str = '月'
      break
    case 'quarter':
      str = '季'
      break
    case 'year':
      str = '年'
      break
    case 'none':
      str = '无'
      break
    case 'rt':
      str = '实时'
      break
    default:
      str = '-'
      break
  }
  return str
}

export default class IndexDetailModal extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      visible: false,
      previewVisible: false,
      isEdit: false,
      isCheck: false,
      titleStr: '查看',
      id: '',
      infoData: {},
      tableOptions: [],
      tblName: '',
      columns: [],
      rows: [],
      initialValue: undefined,
    }

    this.form = React.createRef()
  }

  componentDidMount() {
    getTableList().then(
      (res) => {
        if (res && res.length) {
          this.setState({
            tableOptions: res,
          })
        }
      },
      (error) => {
        console.log(error)
      },
    )
  }

  // 请求关联任务
  getTaskName = (data) => {
    if (data.indexCorrelation && data.indexCorrelation.tblName) {
      getAssociatedTasks({ tableName: data.indexCorrelation.tblName }).then(
        (res) => {
          if (res && res.length) {
            this.setState({
              taskName: res,
            })
          } else {
            this.setState({
              taskName: '',
            })
          }
        },
        (error) => {
          console.log(error)
        },
      )
    }
  }

  // 查看打开弹窗
  // eslint-disable-next-line react/no-unused-class-component-methods
  onCheckOpen = (data) => {
    this.setState({
      infoData: data,
      visible: true,
      isEdit: false,
      isCheck: true,
      titleStr: '查看',
      id: data.id,
      tblName: undefined,
      taskName: '',
      initialValue: undefined,
    }, () => {
      this.getTaskName(data)
    })
  }

  // 关联指标打开弹窗
  // eslint-disable-next-line react/no-unused-class-component-methods
  onEditOpen = (data) => {
    this.setState({
      infoData: data,
      visible: true,
      isEdit: true,
      isCheck: false,
      titleStr: '指标关联',
      id: data.id,
      tblName: undefined,
      taskName: '',
      initialValue: undefined,
    })
  }

  // 变更指标打开弹窗
  // eslint-disable-next-line react/no-unused-class-component-methods
  onChangeOpen = (data) => {
    this.setState({
      infoData: data,
      visible: true,
      isEdit: true,
      isCheck: false,
      titleStr: '变更关联',
      id: data.id,
      tblName: (data.indexCorrelation && data.indexCorrelation.tblName) ? data.indexCorrelation.tblName : undefined,
      taskName: '',
    }, () => {
      this.setState({
        initialValue: (data.indexCorrelation && data.indexCorrelation.tblId) ? String(data.indexCorrelation.tblId) : undefined,
      })
      this.getTaskName(data)
    })
  }

  // 确认回调
  onConfirm = () => {
    this.form.current.validateFields().then(
      (values) => {
        const { id, tblName } = this.state
        const { tblId } = values
        this.setState({ loading: true })
        saveIndexCorrelation({
          id,
          indexCorrelation: {
            tblId,
            tblName,
          },
        }).then(
          (res) => {
            this.setState({
              loading: false,
            }, () => {
              message.success('关联成功')
              this.closeModal()
              this.props.closeCallBack && this.props.closeCallBack()
            })
          },
          (error) => {
            console.log(error)
            this.setState({ loading: false })
          },
        )
      },
    )
  }

  closeModal = () => {
    this.setState({ visible: false })
  }

  // 预览按钮回调
  onPreview = () => {
    const { tblName } = this.state
    if (!tblName || tblName === '') {
      message.warning('请先选择结果表')
      return
    }
    this.setState({ loading: true })
    getPreviewData({ targetTblName: tblName }).then(
      (res) => {
        const { data, status, msg } = res
        if (status === 200) {
          this.setState({
            rows: data.rows ? data.rows : [],
            columns: data.columns ? data.columns : [],
            previewVisible: true,
          })
        } else {
          message.warning(msg)
        }
        this.setState({ loading: false })
      },
      (error) => {
        console.log(error)
        this.setState({ loading: false })
      },
    )
  }

  clickTaskName = (task) => {
    if (task.documentCaptureId) {
      history.push('/dataIntegrate/filesGather')
    } else if (task.nodeId) {
      history.push(`/data-development/offline/workflow-development?taskId=${task.nodeId}`)
    } else if (task.offline_syncId) {
      history.push('/dataIntegrate/offline')
    } else if (task.customFormId) {
      history.push('/dataIntegrate/custom-form')
    }
  }

  handleHeaderInfo = () => {
    const {
      name,
      businessDef,
      calculationRule,
      timeGranularity,
      dataOwnerName,
      analysisDimension,
      remark,
      status,
      updateTime,
      unit,
    } = this.state.infoData
    const list = this.state.isCheck ? [
      [{ key: '指标名称', value: name || '-' }],
      [{ key: '业务定义', value: businessDef || '-' }],
      [{ key: '计算规则', value: calculationRule || '-' }],
      [
        { key: '计量单位', value: unit || '-' },
        { key: '时间粒度', value: timeGranularity ? calTimeGranularityStr(timeGranularity) : '-' },
        // { key: '数据owner', value: dataOwnerName || '-' },
      ],
      [
        { key: '状态', value: status ? '已完成' : '待开发' || '-' },
        { key: '数据更新时间', value: updateTime || '-' },
        { key: '分析维度', value: analysisDimension || '-' },
      ],
      [{ key: '备注', value: remark || '-' }],
    ] : [
      [{ key: '指标名称', value: name || '-' }],
      [{ key: '业务定义', value: businessDef || '-' }],
      [{ key: '计算规则', value: calculationRule || '-' }],
      [
        { key: '时间粒度', value: timeGranularity ? calTimeGranularityStr(timeGranularity) : '-' },
        // { key: '数据owner', value: dataOwnerName || '-' },
        { key: '分析维度', value: analysisDimension || '-' },
      ],
      [{ key: '备注', value: remark || '-' }],
    ]
    return list
  };

  render() {
    const {
      visible, isEdit, titleStr, loading, isCheck, infoData, tableOptions, previewVisible,
      columns, rows, taskName, initialValue,
    } = this.state
    return (
      <Modal
        title={titleStr}
        visible={visible}
        width={1020}
        onCancel={this.closeModal}
        maskClosable={isCheck}
        onOk={this.onConfirm}
        destroyOnClose
        footer={
          isCheck ? null : (
            <>
              <Button
                onClick={this.closeModal}
              >
                取消
              </Button>
              <Button
                onClick={this.onConfirm}
                type="primary"
                loading={loading}
              >
                确定
              </Button>
            </>
          )
        }
      >
        <Spin spinning={loading}>
          <div className={styles.sub_title}>
            <span className={styles.sub_title_txt}>
              基础信息
            </span>
          </div>
          <div className={styles.header_info}>
            {this.handleHeaderInfo().map((item, index) => (
              <Row key={index} className={styles.row}>
                {item.map((rItem, rIndex) => (
                  <Col
                    key={rIndex}
                    className={styles.col}
                    span={item.length === 1 ? 24 : 8}
                  >
                    <span className={styles.key}>{rItem.key}：</span>
                    <span className={`${styles.value} ${styles.text_overflow_single}`} title={rItem.value}>
                      {rItem.value}
                    </span>
                  </Col>
                ))}
              </Row>
            ))}
          </div>
          {
            isCheck && infoData.indexCorrelation && infoData.indexCorrelation.tblName && (
              <>
                <div className={styles.sub_title}>
                  <span className={styles.sub_title_txt}>
                    计算信息
                  </span>
                </div>
                <div className={styles.result_info}>
                  <Form
                    labelCol={{ span: 2 }}
                    wrapperCol={{ span: 22 }}
                  >
                    <Item
                      label="结果表"
                    >
                      {infoData.indexCorrelation.tblName}
                    </Item>
                    <Item
                      label="关联任务"
                    >
                      {
                        (taskName && taskName.length) ? taskName.map((taskItem, index) => (
                          <Tag
                            color="blue"
                            onClick={() => this.clickTaskName(taskItem)}
                            key={`key${index}`}
                            style={{ cursor: (taskItem.nodeId || taskItem.documentCaptureId || taskItem.offline_syncId) ? 'pointer' : 'auto' }}
                          >
                            {taskItem.taskName}
                          </Tag>
                        )) : '--'
                      }
                    </Item>
                    <Item
                      label="数据血缘"
                    >
                      <BloodRelationshipMap id={String(infoData.indexCorrelation.tblId)} />
                    </Item>
                  </Form>
                </div>
              </>
            )
          }
          {
            isEdit && (
              <>
                <div className={styles.sub_title}>
                  <span className={styles.sub_title_txt}>
                    计算信息
                  </span>
                </div>
                <div className={styles.result_info}>
                  <Form
                    labelCol={{ span: 2 }}
                    wrapperCol={{ span: 22 }}
                    ref={this.form}
                  >
                    <Item
                      label="结果表"
                      required
                    >
                      <Input.Group compact className={styles.result_table_select}>
                        <Item
                          noStyle
                          name="tblId"
                          rules={[
                            { required: true, message: '请选择结果表' },
                          ]}
                          initialValue={initialValue}
                        >
                          <Select
                            placeholder="请选择结果表"
                            style={{ width: '100%' }}
                            onChange={(e, option) => {
                              this.setState({
                                tblName: option.title,
                                taskName: '',
                              })
                              this.getTaskName({
                                indexCorrelation: {
                                  tblName: option.title,
                                },
                              })
                            }}
                            showSearch
                            filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          >
                            {
                              tableOptions.map((item) => (
                                <Option
                                  value={String(item.tblId)}
                                  key={item.tblId}
                                  title={item.tableName}
                                >
                                  {item.tableName}
                                </Option>
                              ))
                            }
                          </Select>
                        </Item>
                        <Button
                          type="link"
                          onClick={
                            () => {
                              this.onPreview()
                            }
                          }
                        >
                          数据预览
                        </Button>
                      </Input.Group>
                    </Item>
                    <Item
                      label="关联任务"
                    >
                      {
                        (taskName && taskName.length) ? taskName.map((taskItem, index) => (
                          <Tag
                            color="blue"
                            onClick={() => this.clickTaskName(taskItem)}
                            key={`key${index}`}
                            style={{ cursor: (taskItem.nodeId || taskItem.documentCaptureId || taskItem.offline_syncId) ? 'pointer' : 'auto' }}
                          >
                            {taskItem.taskName}
                          </Tag>
                        )) : '--'
                      }
                    </Item>
                  </Form>
                </div>
              </>
            )
          }
        </Spin>
        <PreviewModal
          visible={previewVisible}
          onCancel={() => this.setState({ previewVisible: false })}
          columns={columns}
          rows={rows}
        />
      </Modal>
    )
  }
}
